package com.example.app.viewmodel

import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.app.model.UserInfoManager
import com.example.app.model.entity.UserInfoEntity
import com.example.app.model.service.UserService
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch

class UserViewModel(context: Context) : ViewModel() {

    private val userInfoManager = UserInfoManager(context)

    private val userService = UserService.instance()


    var userName by mutableStateOf("")

    var password by mutableStateOf("")


    var userInfo: UserInfoEntity? = null
        private set

    init {
        //其实这里可以使用 DataStore 的对象存储，直接存储整个对象
        viewModelScope.launch {
            val userName = userInfoManager.userName.firstOrNull()
            userInfo = if (userName?.isNotEmpty() == true) {
                UserInfoEntity(userName)
            } else {
                null
            }
        }
    }

    //是否已登录
    val logged: Boolean
        get() {
            return userInfo != null
        }

    var loading by mutableStateOf(false)
        private set

    /**
     * 登录操作
     *
     */
    suspend fun login(onClose: () -> Unit) {
        loading = true
        delay(3000)
        val res = userService.signIn(userName, password)
        if ( res.code== 200 && res.data != null) {
            userInfo = res.data
            // userInfoManager.save(userName)
            onClose()
        } else {
            //失败
        }
        loading = false
    }

    fun logout() {
        viewModelScope.launch {
            userInfoManager.clear()
            userInfo = null
        }
    }
}